package com.xwli.webservice.axis.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.axis.AxisEngine;
import org.apache.axis.client.Call;
import org.apache.axis.encoding.XMLType;

import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;

/**
 * @author xwli
 * @date: 2021/10/18 15:36
 * @desc
 * @since JDK 1.8
 */
@Slf4j
public class AxisWebServiceClient {

    public static void main(String[] args) {
        String request = "小李";
        String url = "http://127.0.0.1:8002/services/axiswebservice?wsdl";
        String operationName = "axisHello";
        String paramName = "request";
        String response = callAxisWebService(request,url,operationName,paramName);
        System.out.println("返回响应信息:\n"+response);
    }

    private static String callAxisWebService(String request,String url,String operationName,String paramName){
        String responseBody = "";
        try {
            Call call = initServiceCall(url, operationName);
            //设置请求参数名称
            call.addParameter(paramName, XMLType.XSD_ANYTYPE, ParameterMode.IN);
            // 返回的数据类型
            call.setReturnType(XMLType.XSD_STRING);
            Object returnMessage = call.invoke(new Object[]{request});
            responseBody = String.valueOf(returnMessage);
            return responseBody;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return responseBody;
        }
    }

    private static Call initServiceCall(String url, String operationName) throws ServiceException {
        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(url); //设置请求的url
//      call.setUseSOAPAction(true);
//      call.setSOAPActionURI("");
//      call.setEncodingStyle(null);
//      call.setProperty(Call.CHARACTER_SET_ENCODING, "GB2312");
        call.setProperty(Call.SEND_TYPE_ATTR, Boolean.FALSE);
        call.setProperty(AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
//        call.setSOAPVersion(SOAPConstants.SOAP11_CONSTANTS);
        call.setTimeout(60000);
        call.setOperationName(operationName);// 设置操作的名称
        return call;
    }

}

